package cn.uyunsky.platform.jdbc.page;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.util.WebUtils;


/**
 * 用于分页组件覆盖的类,新的分页组件覆盖此类的bindPageRequest()方法以适合不同的分页创建
 *
 * @author badqiu
 */
public class PageRequestFactory {
    public static final int MAX_PAGE_SIZE = 1000;
    public static final int DEFAULT_PAGE_SIZE = 10;

    static BeanUtilsBean beanUtils = new BeanUtilsBean();

    static {
        // 用于注册日期类型的转换
        String[] datePatterns = new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS", "HH:mm:ss"};
        ConvertRegisterHelper.registerConverters(beanUtils.getConvertUtils(), datePatterns);
        System.out.println("PageRequestFactory.MAX_PAGE_SIZE=" + MAX_PAGE_SIZE);
    }

    public static PageRequest bindPageRequest(PageRequest pageRequest, Map<String, Object> params) {
        return bindPageRequest(pageRequest, params, null);
    }

    public static PageRequest bindPageRequest(PageRequest pageRequest, Map<String, Object> params, String defaultSortColumns) {
        return bindPageRequest(pageRequest, params, defaultSortColumns, DEFAULT_PAGE_SIZE);
    }

    /**
     * 绑定PageRequest的属性值
     */
    public static PageRequest bindPageRequest(PageRequest pageRequest, Map<String, Object> params, String defaultSortColumns,
                                              int defaultPageSize) {
        try {
            beanUtils.copyProperties(pageRequest, params);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("beanUtils.copyProperties() error", e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("beanUtils.copyProperties() error", e.getTargetException());
        }

        /*
        * 对所有数据进行服务器端排序。取数请求中除了可以使用start、limit参数外，
        * 还可以使用 sortBy（是colModel中某item的name属性的值）和 sortDir（升序是asc，降序时是desc）两个参数。
        * */
        int pageNumber = (params.get("start") == null) ? 1 : (Integer) params.get("start");
        int pageSize = (params.get("limit") == null) ? defaultPageSize : (Integer) params.get("limit");
        pageRequest.setPageNumber(pageNumber);
        pageRequest.setPageSize(pageSize);

        String sortBy = (String) params.get("sortBy");
        String sortDir = (String) params.get("sortDir");
        if (sortBy != null && sortDir != null) {
            pageRequest.setSortColumns(sortBy + " " + sortDir);
        } else {
            pageRequest.setSortColumns(defaultSortColumns);
        }

        if (pageRequest.getPageSize() > MAX_PAGE_SIZE) {
            pageRequest.setPageSize(MAX_PAGE_SIZE);
        }
        return pageRequest;
    }

}
